package com.springboot.ww.config.web;

import com.springboot.ww.config.context.TenantContext;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springblade.core.tool.utils.ThreadLocalUtil;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 租户 Web拦截器.
 *
 * @author yangruibo
 */
@Slf4j
public class TenantHandlerInterceptor implements HandlerInterceptor, Ordered {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        TenantContext.unbind();

        String rpcTid = request.getHeader(TenantContext.KEY_TID);
        if (StringUtils.isEmpty(rpcTid)) {
            log.error("租户上下文跟踪，从[{}]请求头中获取租户标识为空", request.getRequestURI());
        } else {
            if (log.isDebugEnabled()) {
                log.debug("租户上下文跟踪，从 RpcContext 绑定租户ID[{}]到 TenantContext", rpcTid);
            }
            TenantContext.bind(rpcTid);
            MDC.put(TenantContext.KEY_TID, rpcTid);
        }

        //FIXME，
        String tToken = ThreadLocalUtil.get(TenantContext.KEY_TOKEN);
        String rpcToken = request.getHeader(TenantContext.KEY_TOKEN);
        if (StringUtils.isEmpty(tToken) && StringUtils.hasText(rpcToken)) {
            ThreadLocalUtil.put(TenantContext.KEY_TOKEN, rpcToken);
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        if (StringUtils.hasText(TenantContext.getTID())) {
            String unbindTid = TenantContext.unbind();
            if (log.isDebugEnabled()) {
                log.debug("租户上下文跟踪，从 TenantContext 解绑租户ID[{}] ", unbindTid);
            }
            MDC.remove(TenantContext.KEY_TID);
        }

        if (StringUtils.hasText(ThreadLocalUtil.get(TenantContext.KEY_TOKEN))) {
            ThreadLocalUtil.remove(TenantContext.KEY_TOKEN);
        }
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 100;
    }
}
